import gpio
import i2c
import os

class SHT30:
    def __init__(self, i2c_id, sda_pin, scl_pin, freq):
        self.i2c_id = i2c_id
        self.sda_pin = sda_pin
        self.scl_pin = scl_pin
        self.freq = freq
        self.i2c_addr = 0x44 << 1
        self.init_gpio()
        self.init_i2c()

    def init_gpio(self):
        gpio.gpio_init(self.sda_pin)
        func = gpio.query_func_value(self.sda_pin, 'I2C1_SDA')
        gpio.set_func(self.sda_pin, func)
        gpio.gpio_init(self.scl_pin)
        func = gpio.query_func_value(self.scl_pin, 'I2C1_SCL')
        gpio.set_func(self.scl_pin, func)

    def init_i2c(self):
        i2c.i2c_init(self.i2c_id, self.freq)
        i2c.write(self.i2c_id, self.i2c_addr, [0x22, 0x36])

    def cal_t(self, t):
        t = t & ~0x3
        t = t * 175 // 65536 - 45
        return t

    def cal_h(self, h):
        h = h & ~0x3
        h = h * 100 // 65536
        return h

    def read(self):
        r, d = i2c.write_read(self.i2c_id, self.i2c_addr, [0xE0, 0x00], 6)
        if r == 0:
            t = (d[0] << 8) | d[1]
            h = (d[3] << 8) | d[4]
            return self.cal_t(t), self.cal_h(h)
        else:
            return None, None

    def temperature(self):
        return self.read()[0]

    def humidity(self):
        return self.read()[1]

    def __del__(self):
        pass

def main():
    i2c_id = 1
    sda_pin = 0
    scl_pin = 1
    freq = 400000

    sht30 = SHT30(i2c_id, sda_pin, scl_pin, freq)

if __name__ == "__main__":
    main()